package org.xxpay.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.xxpay.core.common.constant.MchConstant;
import org.xxpay.core.common.util.DateUtil;
import org.xxpay.core.common.vo.*;
import org.xxpay.core.entity.SysConfig;
import org.xxpay.core.entity.SysConfigExample;
import org.xxpay.core.service.ISysConfigService;
import org.xxpay.service.dao.mapper.SysConfigMapper;

import java.util.*;

/**
 * @author: dingzhiwei
 * @date: 2018/4/27
 * @description:
 */
@Service
public class SysConfigServiceImpl implements ISysConfigService {

    /** 数据库application配置参数 **/
    private static DBApplicationConfig DB_CONFIG = null;

    /** 数据库上传附件配置参数 **/
    private static DBUploadFileConfig DB_UPLOAD_CONFIG = null;

    /** 代付相关设置项 **/
    private static DBAgentpayConfig DB_AGENTPAY_CONFIG = null;

    /** 数据库application配置参数 **/
    private static DBSmsConfig DB_SMS_CONFIG = null;

    /** 数据库 运营平台提醒配置参数 **/
    private static DBSysTipsConfig DB_SYS_TIPS_CONFIG = null;

    /** 缓存数据： 网站设置项  **/
    private static JSONObject SITE_CONFIG = null;

    @Autowired
    private SysConfigMapper sysConfigMapper;

    @Override
    public List<SysConfig> select(String type) {
        SysConfigExample example = new SysConfigExample();
        example.setOrderByClause("orderNum ASC");
        SysConfigExample.Criteria criteria = example.createCriteria();
        criteria.andTypeEqualTo(type);
        return sysConfigMapper.selectByExample(example);
    }

    @Override
    public JSONObject getSysConfigObj(String type) {
        JSONObject obj = new JSONObject();
        List<SysConfig> sysConfigList = select(type);
        if(CollectionUtils.isEmpty(sysConfigList)) return obj;
        for(SysConfig sysConfig : sysConfigList) {
            obj.put(sysConfig.getCode(), sysConfig.getValue());
        }
        return obj;
    }

    @Override
    public int updateAll(List<SysConfig> sysConfigList) {
        if(CollectionUtils.isEmpty(sysConfigList)) return 0;
        int count = 0;
        for(SysConfig sysConfig : sysConfigList) {
            int result = sysConfigMapper.updateByPrimaryKeySelective(sysConfig);
            count += result;
        }
        return count;
    }

    @Override
    public int update(Map<String, String> updateMap) {
        int count = 0;
        Set<String> set = updateMap.keySet();
        for(String k : set) {
            SysConfig sysConfig = new SysConfig();
            sysConfig.setCode(k);
            sysConfig.setValue(updateMap.get(k));
            int result = sysConfigMapper.updateByPrimaryKeySelective(sysConfig);
            count += result;
        }
        return count;
    }

    @Override
    public JSONObject getSysConfig() {
        SysConfigExample example = new SysConfigExample();
        example.setOrderByClause("orderNum ASC");
        JSONObject obj = new JSONObject();
        List<SysConfig> sysConfigList = sysConfigMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(sysConfigList)) return obj;
        for(SysConfig sysConfig : sysConfigList) {
            obj.put(sysConfig.getCode(), sysConfig.getValue());
        }
        return obj;
    }

    @Override
    public String getValByCode(String code) {

        SysConfig record = sysConfigMapper.selectByPrimaryKey(code);
        if(record == null || StringUtils.isEmpty(record.getValue())){
            return "";
        }
        return record.getValue().trim();
    }

    @Override
    public DBApplicationConfig getDBApplicationConfig() {
        if(DB_CONFIG == null) initDBApplicationConfig("applicationConfig");
        return DB_CONFIG;
    }

    @Override
    public DBUploadFileConfig getDBUploadFileConfig() {
        if(DB_UPLOAD_CONFIG == null) initDBApplicationConfig("uploadFile");
        return DB_UPLOAD_CONFIG;
    }

    @Override
    public DBAgentpayConfig getDBAgentpayConfig() {
        if(DB_AGENTPAY_CONFIG == null) initDBApplicationConfig("agentpayConfig");
        return DB_AGENTPAY_CONFIG;
    }

    @Override
    public JSONObject getSiteConfigJSON() {
        if(SITE_CONFIG == null) initDBApplicationConfig("site");
        return SITE_CONFIG;
    }

    @Override
    public DBSmsConfig getSmsConfig() {
        if(DB_SMS_CONFIG == null) initDBApplicationConfig("smsConfig");
        return DB_SMS_CONFIG;
    }

    @Override
    public DBSysTipsConfig getSysTipsConfig() {
        if(DB_SYS_TIPS_CONFIG == null) initDBApplicationConfig("sysTipsConfig");
        return DB_SYS_TIPS_CONFIG;
    }

    @Override
    public synchronized void initDBApplicationConfig(String type) {

        if("applicationConfig".equalsIgnoreCase(type)){
            JSONObject configJSON = this.getSysConfigObj("applicationConfig");
            DB_CONFIG = configJSON.toJavaObject(DBApplicationConfig.class);

        }else if("site".equalsIgnoreCase(type)){
            JSONObject object = selectByCodes(MchConstant.SITE_INFO_CONFIG_KEY);
            SITE_CONFIG = object;

        }else if("uploadFile".equalsIgnoreCase(type)){

            JSONObject result = selectByCodes("uploadFileSaveType", "ossEndpoint", "ossBucketName", "ossAccessKeyId", "ossAccessKeySecret");
            DB_UPLOAD_CONFIG = result.toJavaObject(DBUploadFileConfig.class);
        }else if("agentpayConfig".equalsIgnoreCase(type)){

            JSONObject result = selectByCodes("agentpayOutAccount", "agentpayAuditType", "agentpayCheckRepeatFlag", "agentpayCheckRepeatTime", "agentpaySnatchFlag", "agentpayChoosePayType", "agentpayMchConfigFlag", "agentpayMchConfig2QueryOrderTime");
            DB_AGENTPAY_CONFIG = result.toJavaObject(DBAgentpayConfig.class);

        }else if("smsConfig".equalsIgnoreCase(type)){

            SysConfig record = sysConfigMapper.selectByPrimaryKey("smsConfig");
            DB_SMS_CONFIG = JSON.parseObject(record.getValue()).toJavaObject(DBSmsConfig.class);
        }else if("sysTipsConfig".equalsIgnoreCase(type)){
            JSONObject configJSON = this.getSysConfigObj("sysTips");
            DB_SYS_TIPS_CONFIG = configJSON.toJavaObject(DBSysTipsConfig.class);
        }
    }

    @Override
    @Transactional(transactionManager = "transactionManager", rollbackFor = Exception.class)
    public int cleanData(List<String> list, String createTimeStr) {
        Map param = new HashMap();
        int count = 0;
        if (StringUtils.isNotBlank(createTimeStr)) param.put("createTimeStr", createTimeStr);
        for (String str : list) {
            if (MchConstant.TABLE_NO_PAY_ORDER.equals(str)) {
                param.put("tableName", MchConstant.TABLE_NAME_PAY_ORDER);
            } else if (MchConstant.TABLE_NO_TRANS_ORDER.equals(str)) {
                param.put("tableName", MchConstant.TABLE_NAME_TRANS_ORDER);
            } else if (MchConstant.TABLE_NO_AGENTPAY_ORDER.equals(str)) {
                param.put("tableName", MchConstant.TABLE_NAME_AGENTPAY_ORDER);
            } else if (MchConstant.TABLE_NO_SETT_ORDER.equals(str)) {
                param.put("tableName", MchConstant.TABLE_NAME_SETT_ORDER);
            } else if (MchConstant.TABLE_NO_MCH_ACCOUNT_HISTORY.equals(str)) {
                param.put("tableName", MchConstant.TABLE_NAME_MCH_ACCOUNT_HISTORY);
            } else if (MchConstant.TABLE_NO_AGENT_ACCOUNT_HISTORY.equals(str)) {
                param.put("tableName", MchConstant.TABLE_NAME_AGENT_ACCOUNT_HISTORY);
            }else if (MchConstant.TABLE_NO_MCH_NOTIFY.equals(str)) {
                param.put("tableName", MchConstant.TABLE_NAME_MCH_NOTIFY);
            } else if (MchConstant.TABLE_NO_MCH_BILL.equals(str)) {
                param.put("tableName", MchConstant.TABLE_NAME_MCH_BILL);
            } else if (MchConstant.TABLE_NO_MGR_SYS_LOG.equals(str)){
                param.put("tableName", MchConstant.TABLE_NAME_MGR_SYS_LOG);
            }else if (MchConstant.TABLE_NO_PAY_ORDER_LOG.equals(str)){
                param.put("tableName", MchConstant.TABLE_NAME_PAY_ORDER_LOG);
            } else if (MchConstant.TABLE_STATISTICS_PLAT.equals(str)){
                param.put("type", "1");
                Date str2date = DateUtil.str2date(createTimeStr, DateUtil.FORMAT_YYYY_MM_DD);
                param.put("createTimeStr", str2date);
                param.put("tableName", MchConstant.TABLE_NAME_STATISTICS_PLAT);
            } else if (MchConstant.TABLE_STATISTICS_MCH.equals(str)){
                param.put("type", "1");
                Date str2date = DateUtil.str2date(createTimeStr, DateUtil.FORMAT_YYYY_MM_DD);
                param.put("createTimeStr", str2date);
                param.put("tableName", MchConstant.TABLE_NAME_STATISTICS_MCH);
            } else if (MchConstant.TABLE_STATISTICS_PAY_PASSAGE.equals(str)){
                param.put("type", "1");
                Date str2date = DateUtil.str2date(createTimeStr, DateUtil.FORMAT_YYYY_MM_DD);
                param.put("createTimeStr", str2date);
                param.put("tableName", MchConstant.TABLE_NAME_STATISTICS_PAY_PASSAGE);
            }
            count += sysConfigMapper.cleanData(param);
        }
        return count;
    }

    /** 方法重载 **/
    @Override
    public JSONObject selectByCodes(String... codes) {
        return selectByCodes(Arrays.asList(codes));
    }

    @Override
    public JSONObject selectByCodes(List<String> codes) {

        SysConfigExample exa = new SysConfigExample();
        exa.createCriteria().andCodeIn(codes);
        List<SysConfig> dbResult =  sysConfigMapper.selectByExample(exa);
        JSONObject result = new JSONObject();
        dbResult.stream().forEach(item -> result.put(item.getCode(), item.getValue()));
        return result;
    }

}
